package com.sj.purchase.modules.purchase.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sj.purchase.modules.gy.repository.GySpuRepository;
import com.sj.purchase.modules.purchase.domain.Purchase;
import com.sj.purchase.modules.purchase.repository.PurchaseRepository;
import com.sj.purchase.modules.purchase.views.VPurchase;
import com.sj.purchase.modules.cost.domain.WarehouseEnum;
import com.sj.purchase.modules.gy.repository.GySkuRepository;
import com.sj.purchase.modules.purchase.domain.PurchaseId;
import com.sj.purchase.modules.gy.domain.GySku;
import com.sj.purchase.modules.gy.domain.GySpu;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * Created by icodebug on 17-5-25.
 */
@Service
public class PurchaseService {

    @Value("${sj.sku.stock}")
    private String stockUrl;


    @Autowired
    private PurchaseRepository purchaseRepository;

    @Autowired
    private GySkuRepository skuRepository;

    @Autowired
    private GySpuRepository gySpuRepository;

    public void save(Set<Purchase> purchases){

        purchases.stream().forEach(purchase -> {
            JSONObject mpwStocks = getNowStock(purchase.getId());

            purchase.getStockPrices().stream().forEach(stockPrice -> {

                //查询今日剩余库存
                if(mpwStocks!=null){
                    if(stockPrice.getWarehouseEnum().equals(WarehouseEnum.GUANGZHOUZC) && mpwStocks.containsKey("guangZhou")){
                        stockPrice.setNowStock(mpwStocks.getInteger("guangZhou"));
                    }else if(stockPrice.getWarehouseEnum().equals(WarehouseEnum.JINANZC) && mpwStocks.containsKey("jiNan")){
                        stockPrice.setNowStock(mpwStocks.getInteger("jiNan"));
                    }

                }


                //查询最近两天销量+今日销量
                String startDate = DateFormatUtils.format(DateUtils.addDays(purchase.getId().getCreateDate(),-2),"yyyy-MM-dd");
                String endDate = DateFormatUtils.format(DateUtils.addDays(purchase.getId().getCreateDate(),-1),"yyyy-MM-dd");
                Integer threeDaySales =purchaseRepository.getThreeDaySales(startDate,endDate,purchase.getId().getSkuNo(),stockPrice.getWarehouseEnum().toString());
                threeDaySales = (threeDaySales==null?0:threeDaySales)+(stockPrice.getYesterdaySales()==null?0:stockPrice.getYesterdaySales());
                stockPrice.setThreeDaySales(threeDaySales);

                stockPrice.setPurchase(purchase);
            });

            //计算最终采购数1,2
            purchase.setFinalPurchase12();
            purchaseRepository.saveAndFlush(purchase);
        });

        //purchaseRepository.save(purchases);

    }



    //获取当前库存
    private JSONObject getNowStock(PurchaseId id){
        RestTemplate rt = new RestTemplate();
        Map<String,String> param = new HashMap<>();
        param.put("skuNo",id.getSkuNo());
        param.put("startTime",DateFormatUtils.format(DateUtils.addDays(id.getCreateDate(),-1),"yyyy-MM-dd"));

        //if ("AS0010804,10315705,10315802,AS0010802,AM031573,AM031571,10315905,4030922,AM031352,10313601".indexOf(id.getSkuNo())>-1)
        //    System.out.println("获取当前库存："+stockUrl+"goods/getAllSku"+"    "+JSON.toJSONString(param));

        ResponseEntity<JSONArray> forEntity = rt.getForEntity(stockUrl+"goods/getInventory?skuNo={skuNo}&startTime={startTime}", JSONArray.class, param);
       // System.out.println("获取当前库存result：" + JSON.toJSONString(forEntity.getBody()));

        if (forEntity.getBody()!=null&&forEntity.getBody().size()>0){
            JSONArray warehouses = forEntity.getBody().getJSONObject(0).getJSONArray("warehouse");
            JSONObject warehouse = new JSONObject();
            warehouses.stream().forEach(w->{
                String name = ((JSONObject)w).getString("name");
                int num = ((JSONObject)w).getInteger("num");
                if (name.indexOf("广州")>-1){
                    warehouse.put("guangZhou", num);
                }else if (name.indexOf("总仓")>-1){
                    warehouse.put("jiNan", num);
                }
            });
            return warehouse;
        }

        return null;
    }


    public Map<String,Object> getByDate(Date createDate, Pageable page){
        Page<Purchase> pagePurchases = purchaseRepository.findByIdCreateDate(createDate,page);

        //System.out.println(JSON.toJSONString(pagePurchases)+"          "+pagePurchases.getSize());

        List<VPurchase> vPurchases = new ArrayList<>();

        Map<String,Object> pageVpurchases = new HashMap<>();
        List<Purchase> purchases = pagePurchases.getContent();

        purchases.stream().forEach(purchase -> {




            VPurchase vp = new VPurchase();

            setSku(purchase.getId().getSkuNo(),vp);

            vp.setFinalPurchase(purchase.getFinalPurchase());
            vp.setFinalPurchase1(purchase.getFinalPurchase1());
            vp.setFinalPurchase2(purchase.getFinalPurchase2());
            vp.setLastPrice(purchase.getLastPrice());
            vp.setStockCost(purchase.getStockCost());

            purchase.getStockPrices().stream().forEach(sp->{

                if (sp.getWarehouseEnum().equals(WarehouseEnum.GUANGZHOUZC)){
                    vp.setGnowStock(sp.getNowStock());
                    vp.setGpassage(sp.getPassage());
                    vp.setGthreeDaySales(sp.getThreeDaySales());
                    vp.setGyesterdaySales(sp.getYesterdaySales());
                }else{
                    vp.setNowStock(sp.getNowStock()+vp.getNowStock());
                    vp.setPassage(sp.getPassage()+vp.getPassage());
                    vp.setThreeDaySales(sp.getThreeDaySales()+vp.getThreeDaySales());
                    vp.setYesterdaySales(sp.getYesterdaySales()+vp.getYesterdaySales());
                }

            });

            vPurchases.add(vp);
        });

        pageVpurchases.put("content",vPurchases);
        pageVpurchases.put("totalPages",pagePurchases.getTotalPages());
        pageVpurchases.put("number",pagePurchases.getNumber());
        pageVpurchases.put("size",pagePurchases.getSize());
        pageVpurchases.put("first",pagePurchases.isFirst());
        pageVpurchases.put("last",pagePurchases.isLast());
        pageVpurchases.put("totalElements",pagePurchases.getTotalElements());
        pageVpurchases.put("numberOfElements",pagePurchases.getNumberOfElements());

        //System.out.println("+++++++++++++++++++++++++++++++++");
        return pageVpurchases;
    }


    public void setSku(String skuNo,VPurchase vp){
        GySku sku = skuRepository.findOne(skuNo);
        GySpu spu = null;
        if (sku==null){
            //http://192.168.2.141:8060/goods/getSpu

            RestTemplate rt = new RestTemplate();
            System.out.println("+++++++++++++skuNo:"+skuNo);

            ResponseEntity<JSONObject> forEntity = rt.getForEntity(stockUrl+"goods/getSku?sku={sku}", JSONObject.class, skuNo);
           // System.out.println("查找对不上号的商品result：" + JSON.toJSONString(forEntity.getBody()));
            if (forEntity.getBody()!=null){
                JSONArray jsonArray = forEntity.getBody().getJSONArray("content");
                if(jsonArray==null|| jsonArray.size()<=0){
                    sku = new GySku();
                    sku.setId("000000");
                    sku.setName("对不上号的数据");

                    spu = new GySpu();
                    spu.setId("000000");
                    spu.setName("对不上号的数据");
                    spu.getGyskus().add(sku);
                }else{
                    JSONObject skuObj = jsonArray.getJSONObject(0);
                    sku = new GySku();
                    sku.setId(skuObj.getString("sku"));
                    sku.setName(skuObj.getString("itemName"));

                    spu = new GySpu();
                    spu.setId(skuObj.getString("productNo"));
                    spu.setName(skuObj.getString("shortName"));
                    spu.getGyskus().add(sku);

                    gySpuRepository.saveAndFlush(spu);
                }

            }

        }else{
            spu = sku.getGySpu();
        }


        vp.setSpuNo(spu!=null?spu.getId():null);

        vp.setSkuNo(sku.getId());
        vp.setSkuName(sku.getName());
    }



}
